#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os
import struct

boot = sys.argv[1]

f = open(boot, "rb")

content = f.read()

f.close()

boot_img_hdr_format = 'IIIIIIII'

BOOT_MAGIC_SIZE = 8

kernel_magic = content[0 : BOOT_MAGIC_SIZE]

kernel_size, kernel_addr, ramdisk_size, ramdisk_addr, second_size, second_addr, tags_addr, page_size =  struct.unpack_from(boot_img_hdr_format, content[BOOT_MAGIC_SIZE : BOOT_MAGIC_SIZE + (4 * 8)])

print "kernel_size  = %d page_size = %d kernel_adr = %x" % (kernel_size, page_size, kernel_addr)

kernel_pages = (kernel_size + page_size - 1) / page_size

print "kernel_pages %d" % kernel_pages

kernel = content[page_size : (page_size + kernel_size)]

print len(kernel)

f = open('kernel', "wb")

f.write(kernel)

f.close()


"""
#define BOOT_MAGIC "ANDROID!"
#define BOOT_MAGIC_SIZE 8
#define BOOT_NAME_SIZE 16
#define BOOT_ARGS_SIZE 512
#define BOOT_EXTRA_ARGS_SIZE 1024

	struct boot_img_hdr
{
	unsigned char magic[BOOT_MAGIC_SIZE];

	unsigned kernel_size;  /* size in bytes */
	unsigned kernel_addr;  /* physical load addr */

	unsigned ramdisk_size; /* size in bytes */
	unsigned ramdisk_addr; /* physical load addr */

	unsigned second_size;  /* size in bytes */
	unsigned second_addr;  /* physical load addr */

	unsigned tags_addr;    /* physical addr for kernel tags */
	unsigned page_size;    /* flash page size we assume */
	unsigned unused[2];    /* future expansion: should be 0 */

	unsigned char name[BOOT_NAME_SIZE]; /* asciiz product name */

	unsigned char cmdline[BOOT_ARGS_SIZE];

	unsigned id[8]; /* timestamp / checksum / sha1 / etc */

	/* Supplemental command line data; kept here to maintain
	 * binary compatibility with older versions of mkbootimg */
	unsigned char extra_cmdline[BOOT_EXTRA_ARGS_SIZE];
};
"""
